package com.project.service.server;

import com.project.service.util.ServletFactory;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 处理socket的线程类
 */
public class SocketThread implements Runnable{
    private static String header = "HTTP/1.1 200 OK\r\n" +
            "Content-Type: text/html;charSet=utf-8\r\n" +
            "\r\n";
    private Socket socket;
    public SocketThread(Socket socket){
        this.socket = socket;
        //启动线程
        new Thread(this).start();
    }

    @Override
    public void run() {
        try {
            //从socket中得到读取流，用于接收客户端发送的数据
            InputStream in = socket.getInputStream();
            //从socket中得到写入流，用于将数据发送到客户端
            OutputStream out = socket.getOutputStream();
            //将写入流封装成Response对象，以便更好的向客户端发送数据
            Response resp = new Response(out);
            //将读取流封装成Request对象，以便更好的读取数据
            Request req = new Request(in);

            //得到客户端访问资源URL路径
            String url = req.getUrl();
            //向客户端输出数据
            out.write(header.getBytes());

            //调用工厂方法，得到servlet对象
            Servlet servlet = ServletFactory.getServlet(url);

            if(servlet != null){//客户端请求的是业务组件
                servlet.service(req,resp);
            }
            else {//请求是文件
                resp.sendFile(url);
            }
            out.flush();

            //关闭流
            out.close();
            in.close();
            socket.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
